"use client"

import { useState, useEffect, useRef } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"

interface Library {
  id: string
  name: string
  description: string | null
}

interface Event {
  id: string
  title: string
  description: string | null
  date: string
}

export default function EditLibraryPage({
  params: { id }
}: {
  params: { id: string }
}) {
  const router = useRouter()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [library, setLibrary] = useState<Library | null>(null)
  const [events, setEvents] = useState<Event[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [saving, setSaving] = useState(false)
  const [importing, setImporting] = useState(false)

  useEffect(() => {
    fetchLibrary()
    fetchEvents()
  }, [id])

  async function fetchLibrary() {
    try {
      const response = await fetch(`/api/admin/libraries/${id}`)
      if (!response.ok) throw new Error("加载失败")
      const data = await response.json()
      setLibrary(data)
    } catch (err) {
      setError("无法加载事件库")
    } finally {
      setLoading(false)
    }
  }

  async function fetchEvents() {
    try {
      const response = await fetch(`/api/admin/libraries/${id}/events`)
      if (!response.ok) throw new Error("加载失败")
      const data = await response.json()
      setEvents(data)
    } catch (err) {
      setError("无法加载事件列表")
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!library) return

    setSaving(true)
    try {
      const response = await fetch(`/api/admin/libraries/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: library.name,
          description: library.description
        })
      })

      if (!response.ok) throw new Error("保存失败")
      router.refresh()
    } catch (err) {
      setError("保存事件库失败")
    } finally {
      setSaving(false)
    }
  }

  async function handleImport(e: React.ChangeEvent<HTMLInputElement>) {
    if (!e.target.files?.[0]) return

    const file = e.target.files[0]
    const reader = new FileReader()

    reader.onload = async (event) => {
      if (!event.target?.result) return

      try {
        setImporting(true)
        const csvContent = event.target.result as string
        const response = await fetch(`/api/admin/libraries/${id}/import`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ csv: csvContent })
        })

        if (!response.ok) throw new Error("导入失败")
        
        await fetchEvents()
        if (fileInputRef.current) {
          fileInputRef.current.value = ""
        }
      } catch (err) {
        setError("导入事件失败")
      } finally {
        setImporting(false)
      }
    }

    reader.readAsText(file)
  }

  async function handleDeleteEvent(eventId: string) {
    if (!confirm("确定要删除这个事件吗？")) return

    try {
      const response = await fetch(`/api/admin/events/${eventId}`, {
        method: "DELETE"
      })

      if (!response.ok) throw new Error("删除失败")
      await fetchEvents()
    } catch (err) {
      setError("删除事件失败")
    }
  }

  if (loading) return <div className="text-center p-8">加载中...</div>
  if (error) return <div className="text-red-500 text-center p-8">{error}</div>
  if (!library) return <div className="text-center p-8">事件库不存在</div>

  return (
    <div className="max-w-6xl mx-auto p-8">
      <h1 className="text-2xl font-bold mb-6">编辑事件库</h1>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* 左侧：事件库信息 */}
        <div>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">名称</label>
              <Input
                value={library.name}
                onChange={e => setLibrary(prev => prev ? { ...prev, name: e.target.value } : null)}
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">描述</label>
              <Textarea
                value={library.description || ""}
                onChange={e => setLibrary(prev => prev ? { ...prev, description: e.target.value } : null)}
                rows={4}
              />
            </div>

            <div className="flex space-x-4">
              <Button type="submit" disabled={saving}>
                {saving ? "保存中..." : "保存"}
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push("/admin/libraries")}
              >
                返回
              </Button>
            </div>
          </form>

          <div className="mt-8">
            <h2 className="text-lg font-semibold mb-4">批量导入事件</h2>
            <div className="space-y-4">
              <Input
                ref={fileInputRef}
                type="file"
                accept=".csv"
                onChange={handleImport}
                disabled={importing}
              />
              <div className="text-sm text-gray-500">
                请上传 CSV 文件，格式：标题,描述,日期(YYYY-MM-DD)
              </div>
            </div>
          </div>
        </div>

        {/* 右侧：事件列表 */}
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold">事件列表</h2>
            <Button
              variant="outline"
              size="sm"
              onClick={() => router.push(`/admin/libraries/${id}/events/new`)}
            >
              添加事件
            </Button>
          </div>

          <div className="border rounded-lg overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>标题</TableHead>
                  <TableHead>日期</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {events.map(event => (
                  <TableRow key={event.id}>
                    <TableCell>{event.title}</TableCell>
                    <TableCell>{new Date(event.date).toLocaleDateString()}</TableCell>
                    <TableCell>
                      <div className="space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => router.push(`/admin/events/${event.id}`)}
                        >
                          编辑
                        </Button>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => handleDeleteEvent(event.id)}
                        >
                          删除
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </div>
      </div>
    </div>
  )
} 